package tools

import (
	"github.com/garyburd/redigo/redis"
	"superTools-backend/services/watchConfig"
	"time"
)

/**
* @Author: super
* @Date: 2020-08-21 20:02
* @Description:
**/

/**
* @Author: super
* @Date: 2020-08-13 08:40
* @Description:
**/

var pool *redis.Pool

//创建redis连接池
func newRedisPool() *redis.Pool {
	redisUrl := watchConfig.Redis.Url

	return &redis.Pool{
		MaxIdle:     watchConfig.Redis.MaxIdle,
		MaxActive:   watchConfig.Redis.MaxActive,
		IdleTimeout: 300 * time.Second,
		Dial: func() (redis.Conn, error) {
			conn, err := redis.Dial("tcp", redisUrl)
			if err != nil {
				return nil, err
			}
			//if watchConfig.Redis.Password != "" {
			//	if _, err := conn.Do("AUTH", watchConfig.Redis.Password); err != nil {
			//		conn.Close()
			//		return nil, err
			//	}
			//}
			return conn, nil
		},
		TestOnBorrow: func(conn redis.Conn, t time.Time) error {
			if time.Since(t) < time.Minute {
				return nil
			}
			_, err := conn.Do("PING")
			return err
		},
	}
}

func init() {
	pool = newRedisPool()
}

func GetConn() redis.Conn {
	return pool.Get()
}
